<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="search()">
			<el-form-item label="编制进度" prop="progressStage">
				<el-select v-model="state.queryForm.progressStage" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in progressStage" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="立项时间" prop="yearrange">
				<el-date-picker
					v-model="state.yearrange"
					type="yearrange"
					format="YYYY"
					value-format="YYYY"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					style="width: 100%"
					clearable
				/>
			</el-form-item>
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入" clearable>
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px" @change="handleSelectChange">
							<el-option label="项目编号" value="1" />
							<el-option label="标准名称" value="6" />
							<el-option label="主管部门" value="2" />
							<el-option label="主编单位" value="3" />
							<el-option label="项目负责人" value="4" />
							<el-option label="项目联系人" value="5" />
						</el-select>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="进度状态" prop="progressState">
				<el-select v-model="state.queryForm.progressState" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="(item, index) in progressState" :key="index" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="申请经费">
				<el-input v-model="state.queryForm.minFund" type="number" placeholder="最小" style="width: 100px" clearable></el-input>
				<div style="margin: 0 10px">-</div>
				<el-input v-model="state.queryForm.maxFund" type="number" placeholder="最大" style="width: 100px" clearable></el-input>
			</el-form-item>
			<el-form-item label="请选择专业及重点领域分类" prop="professionalKeyFields">
				<el-select v-model="state.queryForm.professionalKeyFields" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in professionalKeyFields" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>

	<el-card>
		<el-form :inline="true" style="text-align: right" class="anniu">
			<el-form-item v-auth="'M002_S_AssignAdmin'">
				<el-button type="primary" @click="setUser">分配/更换账号</el-button>
			</el-form-item>
			<!-- <el-form-item>
				<el-button type="primary" @click="changeUser">更换账号</el-button>
			</el-form-item> -->
			<el-form-item v-auth="'M002_S_Record'">
				<el-button type="primary" @click="setRecord">备案</el-button>
			</el-form-item>
			<el-form-item v-auth="'M002_S_Upload'">
				<el-button type="primary" @click="setEVersion">上传电子版</el-button>
			</el-form-item>
			<el-form-item v-auth="'M002_S_Export'">
				<el-button type="primary" @click="exportHandle">导出</el-button>
			</el-form-item>
			<el-form-item v-auth="'M002_S_Cancel'">
				<el-button type="primary" @click="revokeHandle">撤消</el-button>
			</el-form-item>
			<el-form-item v-auth="'M002_S_TimeSetting'">
				<el-button type="primary" @click="setTime">时间设置</el-button>
			</el-form-item>
			<el-form-item v-auth="'M002_S_File'">
				<el-button type="primary" :disabled="!hasPermission" @click="archivedHandle">归档</el-button>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'M002_S_CancelPublish'" type="primary" :disabled="disableCancelPublish" @click="cancleReleaseHandle">取消发布</el-button>
			</el-form-item>
		</el-form>

		<el-table ref="multipleTableRef" v-loading="state.dataListLoading" :data="dataList" class="" :row-class-name="tableRowClassName" border>
			<el-table-column type="selection" header-align="center" align="center" width="55" fixed="left" resizable />
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60" fixed="left" resizable></el-table-column>
			<el-table-column prop="projectNumber" label="项目编号" align="center" width="100" fixed="left" resizable sortable />
			<el-table-column prop="standardProjectName" label="标准名称" align="center" width="200" fixed="left" resizable sortable> </el-table-column>
			<el-table-column prop="editorUnitName" label="主编单位" align="center" width="200" resizable sortable> </el-table-column>
			<el-table-column prop="responsibleOrgName" label="主管部门(提出单位)" align="center" width="200" resizable sortable> </el-table-column>
			<el-table-column prop="initiationTime" label="立项时间" align="center" width="120" resizable sortable> </el-table-column>
			<el-table-column prop="actualAllocationFunding" label="实际拨付经费(万元)" align="center" width="110" resizable sortable> </el-table-column>
			<el-table-column prop="sex" label="编制进度" align="center" resizable sortable width="110">
				<template #default="scope">
					<span>{{ dictionaryStore.getDictionaryName('T007', scope.row.progressStage) }}</span>
				</template>
			</el-table-column>

			<el-table-column prop="progressStatusName" label="进度状态" align="center" width="110" resizable sortable> </el-table-column>
			<el-table-column prop="dgbzReviewTime" label="大纲编制评审时间" align="center" width="120" resizable sortable> </el-table-column>
			<el-table-column prop="zqyjReviewTime" label="征求意见评审时间" align="center" width="120" resizable sortable> </el-table-column>
			<el-table-column prop="songsReviewTime" label="送审稿评审时间" align="center" width="120" resizable sortable> </el-table-column>
			<el-table-column prop="baopCompletionTime" label="报批完成时间" align="center" width="120" resizable sortable> </el-table-column>
			<el-table-column prop="releaseTime" label="发布时间" align="center" width="110" resizable sortable> </el-table-column>
			<el-table-column prop="projectManager" label="项目管理员(A/B)" align="center" width="250" resizable sortable> </el-table-column>
			<el-table-column label="备案" align="center" resizable sortable>
				<template #default="scope">
					<div class="cursor" @click="handlelook(scope.row.recordFileList[0])">
						{{ scope.row.recordFileList.length > 0 ? scope.row.recordFileList[0].fileRealName : '' }}
					</div>
				</template>
			</el-table-column>
			<el-table-column label="电子版" align="center" resizable sortable>
				<template #default="scope">
					<div class="cursor" @click="handlelook(scope.row.electronicEditionFileList[0])">
						{{ scope.row.electronicEditionFileList.length > 0 ? scope.row.electronicEditionFileList[0].fileRealName : '' }}
					</div>
				</template>
			</el-table-column>

			<el-table-column label="征求意见稿" align="center" resizable sortable>
				<template #default="scope">
					<div v-if="scope.row.isolicitOpinionsBeforePublish === '1'">
						<span>已取消</span>
					</div>
					<div v-else class="cursor" @click="handlelook(scope.row.solicitOpinionsFileList[0])">
						{{ scope.row.solicitOpinionsFileList.length > 0 ? scope.row.solicitOpinionsFileList[0].fileRealName : '' }}
					</div>
				</template>
			</el-table-column>
			<el-table-column label="发布稿" align="center" resizable sortable>
				<template #default="scope">
					<div v-if="scope.row.ireleaseImplementationStandardPublish === '1'">
						<span>已取消</span>
					</div>
					<div v-else class="cursor" @click="handlelook(scope.row.releaseFileList[0])">
						{{ scope.row.releaseFileList.length > 0 ? scope.row.releaseFileList[0].fileRealName : '' }}
					</div>
				</template>
			</el-table-column>
			<el-table-column label="发布批文" align="center" resizable sortable>
				<template #default="scope">
					<div v-if="scope.row.ireleaseImplementationApprovalPublish === '1'">
						<span>已取消</span>
					</div>
					<div v-else class="cursor" @click="handlelook(scope.row.approvalFileList[0])">
						{{ scope.row.approvalFileList.length > 0 ? scope.row.approvalFileList[0].fileRealName : '' }}
					</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="140">
				<template #default="scope">
					<el-icon
						v-auth="'M002_S_U'"
						:size="16"
						color="#1491FF"
						title="编辑"
						style="cursor: pointer; margin: 0 6px"
						@click="godetail(scope.row, true, 1)"
					>
						<Edit />
					</el-icon>
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="godetail(scope.row, false, 0)">
						<View />
					</el-icon>
					<el-icon :size="16" color="#1491FF" title="进度" style="cursor: pointer; margin: 0 6px" @click="godetail(scope.row, true, 2)">
						<Clock />
					</el-icon>

					<el-icon
						v-auth="'M002_S_RePublsih'"
						:size="16"
						color="#1491FF"
						title="重新发布"
						style="cursor: pointer; margin: 0 6px"
						@click="gRepublish(scope.row)"
						><Refresh
					/></el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
	</el-card>
	<cmDialog v-model="showSetUser" modal-title="分配账号" width="600px">
		<el-table :data="selectList">
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column prop="standardProjectName" label="项目名称" align="center"> </el-table-column>
			<el-table-column prop="projectManagerNameA" label="管理员A" align="center"> </el-table-column>
			<el-table-column prop="projectManagerNameB" label="管理员B" align="center"> </el-table-column>
		</el-table>
		<el-form ref="userFormRef" :model="userForm" :rules="userRules" style="margin-top: 20px">
			<el-form-item label="管理账号A 分配为：" prop="projectManagerA">
				<el-select v-model="userForm.projectManagerA" filterable clearable>
					<el-option v-for="item in userDatalist" :key="item.id" :label="item.cnName" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="管理账号B 分配为：" prop="projectManagerB">
				<el-select v-model="userForm.projectManagerB" filterable clearable>
					<el-option v-for="item in userDatalist" :key="item.id" :label="item.cnName" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<div class="dialog-foot" style="padding-bottom: 12px">
			<el-button @click="showSetUser = false">取消</el-button>
			<el-button type="primary" @click="submitSetUserForm(userFormRef)">确认</el-button>
		</div>
	</cmDialog>
	<cmDialog v-model="showSetRecord" modal-title="备案" width="600px">
		<el-form ref="recordFormRef" :model="recordForm" :rules="recordRules" label-width="130px">
			<el-form-item v-if="selectList && selectList.length > 0" label="标准名称">{{ selectList[0].standardProjectName }}</el-form-item>
			<el-form-item label="备案号" prop="recordNumber">
				<el-input v-model="recordForm.recordNumber" />
			</el-form-item>
			<el-form-item label="备案标准(pdf)" prop="recordFile">
				<el-upload
					:action="uploadApi"
					:headers="uploadHeaders"
					:data="{ extCode: 'RecordFile', remark: '备案标准' }"
					accept=".pdf"
					:file-list="filelistbeian"
					style="width: 70%"
					:on-success="handleUploadSuccess"
					:on-preview="handleUploadPdfPreview"
					:on-error="handleUploadError"
					:on-exceed="handleExceed"
					:on-remove="handleUploadPdfRemove"
				>
					<el-button>上传文件</el-button>
				</el-upload>
			</el-form-item>
		</el-form>
		<div class="dialog-foot" style="padding-bottom: 12px">
			<el-button @click="showSetRecord = false">取消</el-button>
			<el-button type="primary" @click="submitSetRecordForm(recordFormRef)">确认</el-button>
		</div>
	</cmDialog>
	<cmDialog v-model="showSetEVersion" modal-title="电子版" width="600px">
		<el-form ref="eVersionFormRef" :model="recordForm" :rules="eVersionRules" label-width="130px">
			<el-form-item label="标准名称">{{ selectList[0].standardProjectName }}</el-form-item>
			<el-form-item label="电子版" prop="recordFile">
				<el-upload
					:action="uploadApi"
					:headers="uploadHeaders"
					style="width: 70%"
					:data="{ extCode: 'ElectronicVersionFile', remark: '电子版' }"
					:file-list="filelistbeian"
					:on-preview="handleUploadPdfPreview"
					:on-error="handleUploadError"
					:on-exceed="handleExceed"
					:on-remove="handleUploadPdfRemove"
					:on-success="handleUploadSuccess"
				>
					<el-button>上传文件</el-button>
				</el-upload>
			</el-form-item>
		</el-form>
		<div class="dialog-foot" style="padding-bottom: 12px">
			<el-button @click="showSetEVersion = false">取消</el-button>
			<el-button type="primary" @click="submitSetEVersionForm(eVersionFormRef)">确认</el-button>
		</div>
	</cmDialog>
	<cmDialog v-model="showSetTime" modal-title="时间设置" width="800px">
		<el-form label-width="80px">
			<el-form-item label="标准名称">{{ selectList[0].standardProjectName }}</el-form-item>
		</el-form>
		<el-table ref="timeTableRef" :data="setTimeList">
			<el-table-column type="selection" header-align="center" align="center" width="55" fixed="left" />
			<el-table-column prop="name" label="编制阶段" align="center"> </el-table-column>
			<el-table-column prop="deadlineMonth" label="原设定完成时间距下发计划的时长(月)" align="center"> </el-table-column>
			<el-table-column prop="deadlineTime" label="原计划完成日期" align="center"> </el-table-column>
			<el-table-column prop="newdeadlineMonth" label="现设定完成时间距下发计划的时长(月)" align="center">
				<template #default="scope">
					<el-input v-model="scope.row.newdeadlineMonth" type="number" />
				</template>
			</el-table-column>

			<!-- v-if="scope.row.initiationTime && scope.row.deadlineMonth" -->
			<el-table-column prop="newdeadlineTime" label="现计划完成日期" align="center">
				<template #default="scope">
					<div v-if="scope.row.newdeadlineMonth">{{ getNewDate(scope.row.newdeadlineMonth, scope.row.initiationTime) }}</div>
				</template>
			</el-table-column>
		</el-table>
		<div class="dialog-foot" style="padding-bottom: 12px">
			<el-button @click="showSetTime = false">取消</el-button>
			<el-button type="primary" @click="submitSetTime">确认</el-button>
		</div>
	</cmDialog>

	<cmDialog v-model="showcancelPublish" modal-title="取消发布" width="500px">
		<div style="font-size: 16px; margin-top: 20px">请确认需要撤回发布的文件</div>
		<el-form ref="cancelFormRef" :model="cancelForm" :rules="cancelRules" style="margin-top: 20px">
			<el-form-item prop="types">
				<el-checkbox-group v-model="cancelForm.types">
					<el-checkbox v-for="item in cancellist" :key="item.code" :disabled="item.disabled" :label="item.name" :value="item.code"> </el-checkbox>
				</el-checkbox-group>
			</el-form-item>
		</el-form>
		<div class="dialog-foot" style="padding-bottom: 12px">
			<el-button @click="showcancelPublish = false">取消</el-button>
			<el-button type="primary" @click="submitcancelForm()">确认</el-button>
		</div>
	</cmDialog>

	<cmDialog v-model="showRepublish" modal-title="重新发布" width="600px">
		<el-form ref="RepublishFormRef" :model="RepublishForm" :rules="RepublishRules" style="margin-top: 20px">
			<el-form-item prop="types">
				<el-checkbox-group v-model="RepublishForm.types">
					<el-checkbox v-for="item in cancellist" :key="item.code" :disabled="!item.disabled" :label="item.name" :value="item.code"> </el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<!-- @change="handleRepublishChange" -->
			<div v-if="RepublishForm.types.includes('SolicitOpinions_Before_Publish')">
				<div style="font-size: 15px; margin-bottom: 10px">征求意见稿</div>
				<el-form-item label="请上传征求意见稿(PDF)" prop="solicitOpinionsFileList">
					<el-upload
						:action="uploadApi"
						:headers="uploadHeaders"
						accept=".pdf"
						style="width: 70%"
						:data="{ extCode: 'SolicitOpinions_Before_Publish', remark: '征求意见稿' }"
						:file-list="filelistyijian"
						:on-preview="handleUploadPdfPreview"
						:on-error="handleUploadErroryj"
						:on-exceed="handleExceed"
						:on-remove="handleUploadPdfRemoveyj"
						:on-success="handleUploadSuccessyj"
					>
						<el-button>上传文件</el-button>
					</el-upload>
				</el-form-item>
			</div>
			<div v-if="RepublishForm.types.includes('ReleaseImplementationStandard_Publish')">
				<div style="font-size: 15px; margin-bottom: 10px">标准发布批文</div>
				<div class="flex box-row">
					<el-form-item label="批文年度" prop="approvalFileYear">
						<el-date-picker v-model="RepublishForm.approvalFileYear" type="year" placeholder="选择年份" format="YYYY" value-format="YYYY" />
					</el-form-item>
					<el-form-item label="批文号" class="ml20" prop="approvalFileNumber">
						<el-input-number :controls="false" v-model="RepublishForm.approvalFileNumber" placeholder="输入" type="number"></el-input-number>
					</el-form-item>
				</div>
				<el-form-item label="请上传标准发布批文(PDF)" prop="approvalFileList">
					<el-upload
						:action="uploadApi"
						:headers="uploadHeaders"
						accept=".pdf"
						style="width: 70%"
						:data="{ extCode: 'ReleaseImplementationStandard_Publish', remark: '标准发布批文' }"
						:file-list="filelistbiaozhun"
						:on-preview="handleUploadPdfPreview"
						:on-error="handleUploadErrorpw"
						:on-exceed="handleExceed"
						:on-remove="handleUploadPdfRemovepw"
						:on-success="handleUploadSuccesspw"
					>
						<el-button>上传文件</el-button>
					</el-upload>
				</el-form-item>
			</div>

			<div v-if="RepublishForm.types.includes('ReleaseImplementationApproval_Publish')">
				<div style="font-size: 15px; margin-bottom: 10px">发布标准</div>

				<el-form-item label="请上传发布标准(PDF)" prop="releaseFileList">
					<el-upload
						:action="uploadApi"
						:headers="uploadHeaders"
						accept=".pdf"
						style="width: 70%"
						:data="{ extCode: 'ReleaseImplementationApproval_Publish', remark: '发布标准' }"
						:file-list="filelistfabu"
						:on-preview="handleUploadPdfPreview"
						:on-error="handleUploadErrorbz"
						:on-exceed="handleExceed"
						:on-remove="handleUploadPdfRemovebz"
						:on-success="handleUploadSuccessbz"
					>
						<el-button>上传文件</el-button>
					</el-upload>
				</el-form-item>
			</div>
		</el-form>
		<div class="dialog-foot" style="padding-bottom: 12px">
			<el-button @click="showRepublish = false">取消</el-button>
			<el-button type="primary" @click="submitRepublishForm()">确认</el-button>
		</div>
	</cmDialog>
	<addDialog
		v-model="showAddDialog"
		:edit-id="editId"
		:is-view="isView"
		:is-audit="isAudit"
		:show-audit="true"
		@submit-success="addSuccess"
	></addDialog>
</template>
<script setup lang="ts">
import {
	assignAccountApi,
	cancelProgressAndApplyApi,
	cancelPublishProgressApi,
	documentationApi,
	doPublishApi,
	doRecordApi,
	submitElectronicEditionApi,
	timeSettingApi,
	ueryProgressListApi,
	updateTimeSettingApi
} from '@/api/bianzhi'
import { filePreviewById, filePreviewByName } from '@/api/sys/upload'
import { queryUserApi } from '@/api/system/rbac'
import cmDialog from '@/components/cm-dialog/index.vue'
import { router } from '@/router'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import type { FormInstance, TableInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import addDialog from '../../Sproject/declare/components/addDialog.vue'
const dictionaryStore = useDictionaryStore()
const userStore = useUserStore()
const route = useRoute()
const pendingStatus = route.query.pendingStatus

const state = reactive({
	queryForm: {
		progressStage: [],
		startYear: '',
		endYear: '',
		minFund: '',
		maxFund: '',
		professionalKeyFields: [],
		projectNumber: '',
		responsibleOrgName: '',
		editorUnitName: '',
		contactName: '',
		responsiblePerson: '',
		standardProjectName: '',
		projectManagerA: '',
		projectManagerB: '',
		progressState: [],
		pendingStatus: pendingStatus || ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null,
	yearrange: []
})
const filelistbiaozhun = ref([])
const filelistyijian = ref([])
const filelistfabu = ref([])
const filelistbeian = ref([])
const showRepublish = ref<boolean>(false)
const RepublishFormRef = ref<FormInstance>()
const RepublishForm = reactive({
	types: [],
	id: null,
	approvalFileYear: null,
	approvalFileNumber: null,
	solicitOpinionsFileList: [], //征求意见稿
	approvalFileList: [], //标准发布批文
	releaseFileList: [] //发布标准
})
const RepublishRules = reactive({
	types: [{ required: true, message: '请选择', trigger: 'change' }],
	// solicitOpinionsFileList: [{ required: true, message: '请选择', trigger: 'change' }],
	// 征求意见稿文件列表的验证
	solicitOpinionsFileList: [
		{
			required: true,
			message: '请上传征求意见稿文件',
			trigger: 'change'
		}
	],

	approvalFileYear: [
		{
			required: true,
			message: '请选择批文年度',
			trigger: 'change'
		}
	],

	approvalFileNumber: [
		{
			required: true,
			message: '请输入申请经费',
			trigger: 'change'
		}
	],
	approvalFileList: [
		{
			required: true,
			message: '请上传标准发布批文文件',
			trigger: 'change'
		}
	],

	releaseFileList: [
		{
			required: true,
			message: '请上传发布标准文件',
			trigger: 'change'
		}
	]
})

const cancelFormRef = ref(null)
const cancelForm = reactive({
	types: []
})
const cancelRules = reactive({
	types: [{ required: true, message: '请选择', trigger: 'change' }]
})

const cancellist = ref([
	{ name: '征求意见函', code: 'SolicitOpinions_Before_Publish', disabled: false },
	{ name: '标准发布批文', code: 'ReleaseImplementationStandard_Publish', disabled: false },
	{ name: '发布标准', code: 'ReleaseImplementationApproval_Publish', disabled: false }
])

const showcancelPublish = ref<boolean>(false)
const progressStage = dictionaryStore.getDictionaryByCode('T007')
const progressState = dictionaryStore.getDictionaryByCode('T014')
// const progressState = [
// 	{
// 		name: '正常',
// 		code: '1'
// 	},
// 	{
// 		name: '滞后',
// 		code: '2'
// 	},
// 	{
// 		name: '撤销',
// 		code: '3'
// 	},
// 	{
// 		name: '归档',
// 		code: '4'
// 	}
// ]
const professionalKeyFields = dictionaryStore.getDictionaryByCode('T003')
const multipleTableRef = ref<TableInstance>()
const dataList = ref([])
const userDatalist = ref([])
const showSetUser = ref<boolean>(false)
// const isChangeUser = ref<boolean>(false)
const selectList = ref([])
const userFormRef = ref<FormInstance>()
const userForm = reactive({
	ids: [],
	projectManagerA: '',
	projectManagerB: ''
})
const userRules = reactive<any>({
	projectManagerA: [{ required: true, message: '请选择', trigger: 'change' }],
	projectManagerB: [{ required: true, message: '请选择', trigger: 'change' }]
})

const showSetRecord = ref<boolean>(false)
const recordFormRef = ref<FormInstance>()
const recordForm = reactive({
	recordNumber: '',
	recordFile: '',
	fileInfo: []
})
const recordRules = reactive<any>({
	recordNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
	recordFile: [{ required: true, message: '请上传文件', trigger: 'blur' }]
})
const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const showSetEVersion = ref<boolean>(false)
const eVersionFormRef = ref<FormInstance>()
const eVersionRules = reactive<any>({
	recordFile: [{ required: true, message: '请上传文件', trigger: 'blur' }]
})
const showSetTime = ref<boolean>(false)
const setTimeList = ref([])
const timeTableRef = ref<TableInstance>()

const showAddDialog = ref<boolean>(false)
const editId = ref<string>('')
const isView = ref<boolean>(false)
const isAudit = ref<boolean>(false)

watch(
	() => showSetUser.value,
	newVal => {
		if (newVal == false) {
			userForm.ids = []
			userForm.projectManagerA = ''
			userForm.projectManagerB = ''
			selectList.value = []
			// isChangeUser.value = false
		}
	}
)

const disableCancelPublish = computed(() => {
	if (!multipleTableRef.value) {
		return true
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()
	if (selectedRows.length !== 1) {
		return true
	}
	console.log('disableCancelPublish', selectedRows.some(row => row.progressStatusName != '发布'));
	return selectedRows.some(row => row.progressStatusName != '发布')
})

const hasPermission = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.progressStatusName == '发布')

	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})

// const handleDownload = async (file: any) => {
// 	// 替换为你的下载逻辑
// 	console.log('下载功能待实现', file)
// 	const url = window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + `/api/files/${file[0].id}/downloadByFileId`
// 	await downloadFile(url, file[0])
// }
const handlelook = async (file: any) => {
	// 替换为你的下载逻辑
	if (file) {
		filePreviewById(file.id).then(res => {
			window.open(res.data.url)
		})
	}
}
// const handleRepublishChange = (val: any) => {
// 	RepublishFormRef.value?.resetFields()
// }
const handleUploadPdfPreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

const gRepublish = (row: any) => {
	showRepublish.value = true
	RepublishFormRef.value?.resetFields()
	RepublishForm.id = row.id

	const aa = [
		{
			name: '征求意见函',
			code: 'SolicitOpinions_Before_Publish',
			disabled: row.isolicitOpinionsBeforePublish == '1' ? true : false
		},
		{
			name: '标准发布批文',
			code: 'ReleaseImplementationStandard_Publish',
			disabled: row.ireleaseImplementationApprovalPublish == '1' ? true : false
		},
		{
			name: '发布标准',
			code: 'ReleaseImplementationApproval_Publish',
			disabled: row.ireleaseImplementationStandardPublish == '1' ? true : false
		}
	]

	console.log(aa, 'sgsg')
	cancellist.value = aa
}
const handleExceed: UploadProps['onExceed'] = files => {
	ElMessageBox.confirm('只能上传一份文件，若要替换，请先删除已有文件', '温馨提示', {
		showConfirmButton: false,
		cancelButtonText: '知道了',
		type: 'warning'
	})
}

const handleUploadError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	filelistbeian.value = filelistbeian.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	recordForm.fileInfo = filelistbeian.value
}
const handleUploadPdfRemove = (file: UploadRawFile) => {
	filelistbeian.value = []
	recordForm.fileInfo = []
}

const handleUploadErroryj = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	filelistyijian.value = filelistyijian.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	RepublishForm.solicitOpinionsFileList = filelistyijian.value
}
const handleUploadPdfRemoveyj = (file: UploadRawFile) => {
	filelistyijian.value = []
	RepublishForm.solicitOpinionsFileList = []
}
const handleUploadSuccessyj = (res: any, uploadFile: any) => {
	if (res.code == '200') {
		filelistyijian.value.push(res.data)
		RepublishForm.solicitOpinionsFileList = filelistyijian.value
	} else {
		handleUploadErroryj(res, uploadFile)
	}
}

const handleUploadErrorpw = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	filelistbiaozhun.value = filelistbiaozhun.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	RepublishForm.approvalFileList = filelistbiaozhun.value
}
const handleUploadPdfRemovepw = (file: UploadRawFile) => {
	filelistbiaozhun.value = []
	RepublishForm.approvalFileList = []
}
const handleUploadSuccesspw = (res: any, uploadFile: any) => {
	if (res.code == '200') {
		filelistbiaozhun.value.push(res.data)
		RepublishForm.approvalFileList = filelistbiaozhun.value
	} else {
		handleUploadErrorpw(res, uploadFile)
	}
}
const handleUploadErrorbz = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	filelistfabu.value = filelistfabu.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	RepublishForm.releaseFileList = filelistfabu.value
}
const handleUploadPdfRemovebz = (file: UploadRawFile) => {
	filelistfabu.value = []
	RepublishForm.releaseFileList = []
}
const handleUploadSuccessbz = (res: any, uploadFile: any) => {
	if (res.code == '200') {
		filelistfabu.value.push(res.data)
		RepublishForm.releaseFileList = filelistfabu.value
	} else {
		handleUploadErrorbz(res, uploadFile)
	}
}
const handleSelectChange = () => {
	state.keyword = ''
	state.queryForm.projectNumber = ''
	state.queryForm.responsibleOrgName = ''
	state.queryForm.editorUnitName = ''
	state.queryForm.contactName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.standardProjectName = ''
}
const godetail = (row, a, b) => {
	router.push({
		path: '/bzjddetail',
		query: {
			id: row.id,
			edit: a,
			progressStatus: row.progressStatus,
			active: b,
			progressStage: row.progressStage,
			progressColor: row.progressColor,
			isshen: 'true',
			name: row.standardProjectName,
			pid: row.projectInfoId
		}
	})
}

watch(
	() => showSetRecord.value,
	newVal => {
		if (newVal == false) {
			recordForm.recordNumber = ''
			recordForm.recordFile = ''
			recordForm.fileInfo = []
			selectList.value = []
		}
	}
)

watch(
	() => showSetEVersion.value,
	newVal => {
		if (newVal == false) {
			recordForm.recordNumber = ''
			recordForm.recordFile = ''
			recordForm.fileInfo = []
			//	selectList.value = []
		}
	}
)

watch(
	() => showSetTime.value,
	newVal => {
		if (newVal == false) {
			setTimeList.value = []
			selectList.value = []
		}
	}
)

watch(
	() => showAddDialog.value,
	newVal => {
		if (newVal == false) {
			editId.value = ''
			isView.value = false
			isAudit.value = false
		}
	}
)

const getDataList = () => {
	switch (state.keyType) {
		case '1':
			state.queryForm.projectNumber = state.keyword
			break
		case '2':
			state.queryForm.responsibleOrgName = state.keyword
			break
		case '3':
			state.queryForm.editorUnitName = state.keyword
			break
		case '4':
			state.queryForm.contactName = state.keyword
			break
		case '5':
			state.queryForm.responsiblePerson = state.keyword
			break
		case '6':
			state.queryForm.standardProjectName = state.keyword
			break
	}
	state.queryForm.startYear = state.yearrange[0] || ''
	state.queryForm.endYear = state.yearrange[1] || ''
	state.dataListLoading = true
	ueryProgressListApi({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		dataList.value = res.data.list || []
		state.total = res.data.total || 0
	})
}

const tableRowClassName = ({ row }: { row: any }) => {
	if (row.progressColor) {
		return row.progressColor
	}
}

const search = () => {
	state.pageNum = 1
	getDataList()
}

// const godetail = () => {
// 	router.push({
// 		path: '/bzjddetail'
// 	})
// }

const reset = () => {
	state.queryForm.progressStage = []
	state.queryForm.startYear = ''
	state.queryForm.endYear = ''
	state.queryForm.minFund = ''
	state.queryForm.maxFund = ''
	state.queryForm.professionalKeyFields = []
	state.queryForm.projectNumber = ''
	state.queryForm.responsibleOrgName = ''
	state.queryForm.editorUnitName = ''
	state.queryForm.contactName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.standardProjectName = ''
	state.queryForm.projectManagerA = ''
	state.queryForm.projectManagerB = ''
	state.queryForm.progressState = []
	state.queryForm.pendingStatus = ''
	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	state.yearrange = []
	getDataList()
}

const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}

const getUserList = () => {
	queryUserApi({
		cnName: '',
		loginName: '',
		pageIndex: 1,
		pageSize: 1000,
		roleCode: 'ZZADMIN,SHZZ'
	}).then(res => {
		userDatalist.value = res.data.list
	})
}

const setUser = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}
		// const hasProjectManager = selectedRows.some(row => row.projectManager)
		// if (hasProjectManager) {
		// 	throw new Error('选择的项目中已经存在项目管理员，无法分配！')
		// }
		selectList.value = selectedRows
		if (selectList.value.length == 1) {
			userForm.projectManagerA = selectList.value[0].projectManagerA
			userForm.projectManagerB = selectList.value[0].projectManagerB
		}
		showSetUser.value = true
	} catch (error) {
		ElMessage.error(error.message)
	}
}

const submitSetUserForm = async (formRef: FormInstance) => {
	if (!formRef) {
		return
	}
	await formRef.validate((valid, fields) => {
		if (valid) {
			userForm.ids = selectList.value.map(i => i.id)
			assignAccountApi(userForm).then(res => {
				ElMessage({
					type: 'success',
					message: '操作成功'
				})
				showSetUser.value = false
				getDataList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const setRecord = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		if (selectedRows.length > 1) {
			throw new Error('目前只能选择一个项目')
		}
		filelistbeian.value = []
		recordForm.fileInfo = []
		selectList.value = selectedRows
		showSetRecord.value = true
	} catch (error) {
		ElMessage.error(error.message)
	}
}

const handleUploadSuccess = (res: any, uploadFile: any) => {
	if (res.code == '200') {
		recordForm.recordFile = res.data.fileRealName
		filelistbeian.value.push(res.data)
		recordForm.fileInfo[0] = res.data
	} else {
		handleUploadError(res, uploadFile)
	}
}

const submitSetRecordForm = async (formRef: FormInstance) => {
	if (!formRef) {
		return
	}
	await formRef.validate((valid, fields) => {
		if (valid) {
			const shuzu = recordForm.fileInfo.map((item: any) => {
				return {
					extCode: item.extCode,
					fileExtName: item.fileExtName,
					filePath: item.filePath,
					fileRealName: item.fileRealName,
					fileSize: item.fileSize,
					id: item.id,
					remark: item.remark,
					systemFileName: item.systemFileName
				}
			})
			doRecordApi({
				id: selectList.value[0].id,
				recordNumber: recordForm.recordNumber,
				filesRecordList: shuzu
			}).then(() => {
				filelistbeian.value = []
				recordForm.fileInfo = []
				ElMessage({
					type: 'success',
					message: '操作成功'
				})
				showSetRecord.value = false

				getDataList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const setEVersion = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		if (selectedRows.length > 1) {
			throw new Error('目前只能选择一个项目')
		}
		filelistbeian.value = []
		recordForm.fileInfo = []
		selectList.value = selectedRows
		showSetEVersion.value = true
	} catch (error) {
		ElMessage.error(error.message)
	}
}

const submitSetEVersionForm = async (formRef: FormInstance) => {
	if (!formRef) {
		return
	}
	await formRef.validate((valid, fields) => {
		if (valid) {
			recordForm.fileInfo.forEach((item: any) => {
				delete item.uid
			})

			const shuzu = recordForm.fileInfo.map((item: any) => {
				return {
					extCode: item.extCode,
					fileExtName: item.fileExtName,
					filePath: item.filePath,
					fileRealName: item.fileRealName,
					fileSize: item.fileSize,
					id: item.id,
					remark: item.remark,
					systemFileName: item.systemFileName
				}
			})
			submitElectronicEditionApi({
				id: selectList.value[0].id,
				filesRecordList: shuzu
			}).then(() => {
				filelistbeian.value = []
				recordForm.fileInfo = []
				ElMessage({
					type: 'success',
					message: '操作成功'
				})
				showSetEVersion.value = false

				getDataList()
			})
		}
	})
}

const exportHandle = () => {
	try {
		// const selectedRows = multipleTableRef.value.getSelectionRows();
		// if (selectedRows.length == 0) {
		// 	throw new Error('请至少选择一个项目')
		// }
		// const ids = selectedRows.map(item => {
		// 	return item.id
		// })
		const param = {
			// ids: ids,
			progressState: [],
			// progressStateA: '',
			// progressStateB: '',
			// progressStateC: '',
			// progressStateD: '',
			...state.queryForm
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/preparationProgress/exportProgress',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '标准编制导出文件.xls'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const revokeHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		if (selectedRows.length > 1) {
			throw new Error('目前只能选择一个项目')
		}
		ElMessageBox.confirm(`是否撤销'${selectedRows[0].standardProjectName}'`, '温馨提示', {
			confirmButtonText: '撤销',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			cancelProgressAndApplyApi({
				id: selectedRows[0].id
			}).then(() => {
				ElMessage({
					type: 'success',
					message: '操作成功'
				})
				getDataList()
			})
		})
	} catch (error) {
		ElMessage.error(error.message)
	}
}

const archivedHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		if (selectedRows.length > 1) {
			throw new Error('目前只能选择一个项目')
		}
		ElMessageBox.confirm(`是否归档'${selectedRows[0].standardProjectName}'`, '温馨提示', {
			confirmButtonText: '归档',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			documentationApi({
				id: selectedRows[0].id
			}).then(() => {
				ElMessage({
					type: 'success',
					message: '操作成功'
				})
				getDataList()
			})
		})
	} catch (error) {
		ElMessage.error(error.message)
	}
}

const cancelselcetlist = ref([])
const cancleReleaseHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		if (selectedRows.length > 1) {
			throw new Error('目前只能选择一个项目')
		}
		const row = selectedRows[0]

		const aa = [
			{ name: '征求意见函', code: 'SolicitOpinions_Before_Publish', disabled: row.isolicitOpinionsBeforePublish == '0' ? true : false },
			{
				name: '标准发布批文',
				code: 'ReleaseImplementationStandard_Publish',
				disabled: row.ireleaseImplementationApprovalPublish == '0' ? true : false
			},
			{
				name: '发布标准',
				code: 'ReleaseImplementationApproval_Publish',
				disabled: row.ireleaseImplementationStandardPublish == '0' ? true : false
			}
		]
		cancellist.value = aa

		cancelselcetlist.value = selectedRows.map(item => {
			return item.id
		})

		showcancelPublish.value = true
	} catch (error) {
		ElMessage.error(error.message)
	}
}

const submitRepublishForm = () => {
	RepublishFormRef.value.validate((valid, fields) => {
		if (valid) {
			ElMessageBox.confirm(`是否重新发布`, '温馨提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				doPublishApi(RepublishForm).then(() => {
					ElMessage({
						type: 'success',
						message: '发布成功'
					})
					showRepublish.value = false
					getDataList()
				})
			})
		}
	})
}

const submitcancelForm = () => {
	cancelFormRef.value.validate((valid, fields) => {
		if (valid) {
			ElMessageBox.confirm(`是否取消发布`, '温馨提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				cancelPublishProgressApi({
					ids: cancelselcetlist.value,
					types: cancelForm.types
				}).then(() => {
					ElMessage({
						type: 'success',
						message: '操作成功'
					})
					showcancelPublish.value = false
					getDataList()
				})
			})
		}
	})
}
const setTime = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		if (selectedRows.length > 1) {
			throw new Error('目前只能选择一个项目')
		}
		showSetTime.value = true
		selectList.value = selectedRows
		timeSettingApi({
			id: selectedRows[0].id
		}).then(res => {
			setTimeList.value = res.data
		})
	} catch (error) {
		ElMessage.error(error.message)
	}
}

const addSuccess = (e: any) => {
	editId.value = ''
	showAddDialog.value = false
	reset()
}

const handleView = (row: any) => {
	isView.value = true
	editId.value = row.projectInfoId
	isAudit.value = false
	showAddDialog.value = true
}

const handleEdit = (row: any) => {
	editId.value = row.projectInfoId
	isView.value = false
	isAudit.value = true
	showAddDialog.value = true
}

const getNewDate = (month, date) => {
	const currentDate = new Date(date)
	if (isNaN(currentDate.getTime())) {
		throw new Error('Invalid date')
	}

	const year = currentDate.getFullYear()
	const currentMonth = currentDate.getMonth()
	const day = currentDate.getDate()
	const newMonth = Number(currentMonth) + Number(month)
	const newYear = year + Math.floor(newMonth / 12)
	const adjustedMonth = newMonth % 12

	const newDate = new Date(newYear, adjustedMonth, day)

	if (newDate.getDate() !== day) {
		newDate.setDate(0)
	}
	const formattedDate = `${newDate.getFullYear()}-${String(newDate.getMonth() + 1).padStart(2, '0')}-${String(newDate.getDate()).padStart(2, '0')}`
	return formattedDate
}

const submitSetTime = () => {
	try {
		const selectedRows = timeTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个阶段')
		}
		if (selectedRows.some((r: any) => !r.newdeadlineMonth)) {
			throw new Error('请设置时长')
		}
		const data = selectedRows.map((r: any) => {
			return {
				deadlineMonth: r.newdeadlineMonth,
				name: r.name
			}
		})
		updateTimeSettingApi({
			id: selectList.value[0].id,
			dataList: data
		}).then(res => {
			ElMessage.success('设置成功')
			showSetTime.value = false
			getDataList()
		})
	} catch (error) {
		ElMessage.error(error.message)
	}
}

onMounted(() => {
	getDataList()
	getUserList()
})
</script>

<style lang="scss" scoped>
.dialog-foot {
	display: flex;
	justify-content: center;
	padding-top: 20px;
	margin-bottom: 10px;
}

.anniu .el-form-item {
	margin-right: 10px !important;
}

::v-deep(.el-input-number .el-input__inner) {
	text-align: left;
}
</style>
